<template>
  <div>
    <BKMapDrawer
      position="right"
      bottom="6"
      top="6"
      :z-index="65"
      width="550"
      :menus="menus"
      item-class="custom-menu-item"
      active-item-class="custom-active-menu-item"
      @expandChange="expand = $event"
    >
      <div class="drawer-content d-flex-c">
        <BKForm
          :items="conditions"
          ref="conditionForm"
          class="condition-form"
          label-width="auto"
          button-size="small"
          submit-text="查询"
          submit-icon="ri-search-line"
          reset-icon="ri-brush-3-line"
          @submit="search"
          @reset="reset"
        />
        <ConfigGrid
          ref="grid"
          :configs="configs"
          :condition-form-props="{size: 'small',buttonSize: 'small',submitIcon: 'ri-search-line', resetIcon: 'ri-brush-3-line'}"
          :pager-config="{layouts: ['PrevPage', 'Number', 'NextPage', 'Sizes', 'Total']}"
          is-external-condition
          @conditionLoaded="conditionLoaded"
          @currentChange="currentChange"
          class="flex-1 overflow-hidden"
          :has-add="false"
          @operation="handleOperation"
          @formSaveSuccess="getMapData()"
          @afterRemove="getMapData()"
          :page-size="200"
          :page-sizes="[10,20,50,100,200]"
        >
          <template #toolbarLeftPrepend>
            <el-dropdown
              class="m-r-mini"
              @command="handleCommand"
            >
              <el-button
                size="mini"
                type="primary"
              >
                新增<i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="Point">
                  新增点
                </el-dropdown-item>
                <el-dropdown-item command="LineString">
                  新增线
                </el-dropdown-item>
                <!-- <el-dropdown-item command="Polygon">
                  新增面
                </el-dropdown-item> -->
              </el-dropdown-menu>
            </el-dropdown>
          </template>
          <template #toolbarLeftAppend>
            <!-- <el-dropdown
              class="m-l-mini"
              @command="stationHandleCommand"
            >
              <el-button
                size="mini"
                type="primary"
                plain
              >
                参编雨量站<i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="templateDownload">
                  模板下载
                </el-dropdown-item>
                <el-dropdown-item command="handleImport">
                  参编雨量站导入
                </el-dropdown-item>
                <el-dropdown-item command="openStationManagement">
                  参编雨量站管理
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown> -->
            <el-button
              size="mini"
              type="primary"
              plain
              @click="openStationManagement()"
            >
              参编雨量站
            </el-button>
            <el-upload
              action="/ysjc/byjcg/importCz"
              :http-request="importData"
              accept=".xlsx"
              class="import-upload m-l-mini"
              :show-file-list="false"
              v-show="false"
            >
              <el-button
                size="mini"
                type="primary"
                plain
                ref="importButton"
              >
                参编雨量站导入
              </el-button>
            </el-upload>
            <el-button
              type="primary"
              plain
              size="mini"
              @click="openModal"
              style="margin-left: 10px;"
            >
              点面折减系数
            </el-button>
          </template>
        </ConfigGrid>
      </div>
      <SearchStation
        class="follower-top"
        :ls="BZLSLX"
        need-search-tzz
        ref="searchStation"
        :expand="expand"
      />
      <Legend
        class="follower-bottom"
        :list="legends"
        content-width="190px"
      />
    </BKMapDrawer>
    <OperationPanel
      ref="panel"
      class="panel-position"
      placement="bottom-start"
      :has-map-mode="false"
    />
    <PointerCoordinates style="left: 8px;bottom: 10px;background: #011145e6;box-shadow: 0 0 9px 0 #042ea5 inset;z-index: 99;" />
    <BKModal
      v-model="visible"
      width="70%"
      height="80%"
      title="参编雨量站管理"
    >
      <ConfigGrid
        ref="stationGrid"
        :configs="stationConfigs"
        :config-form-props="configFormProps"
      >
        <template #toolbarLeftAppend>
          <el-button
            size="mini"
            type="primary"
            plain
            @click="templateDownload()"
          >
            模板下载
          </el-button>
          <el-button
            size="mini"
            type="primary"
            plain
            @click="handleImport()"
          >
            导入
          </el-button>
        </template>
      </ConfigGrid>
    </BKModal>
    <TableModal ref="modal" />
  </div>
</template>

<script>
import PointerCoordinates from '@/components/geo-map/pointer-coordinates.vue'
import OperationPanel from '@/components/geo-map/operation-panel.vue'
import SearchStation from '../components/search-station.vue'
import TableModal from './table-modal.vue'

import MapEventsMixins from '@/utils/mixins/map-events.mixins.js'
import MapMixins from '@/utils/mixins/map.mixins.js'

const layerCodeMap = {
  1: 'dnpj',
  2: 'bcxs',
  3: 'scyl'
}

export default {
  name: 'RainStormAchievements',
  components: {
    PointerCoordinates,
    OperationPanel,
    SearchStation,
    TableModal
  },
  mixins: [MapEventsMixins, MapMixins],
  data () {
    return {
      configFormProps: { customValidator: this.customValidator },
      menus: [{ text: '暴雨图集成果', value: '1' }],
      configs: {
        isView: false,
        appId: 'YSJC',
        bzCode: 'YSJC',
        metaSet: 'YSQJC_BYTJ_BYTJCG',
        afterFetchColumns: this.afterFetchColumns,
        module: '数据',
        afterFormLoading: this.afterFormLoading,
        formItemProcessor: this.formItemProcessor,
        prepandOperations: [
          { text: '编辑空间对象', operationName: 'editSpot', class: 'ri-shape-line', authCode: '' }
        ],
        customEditMethod: this.customEditMethod,
        operationWidth: 100,
        modal: {
          width: 400
        }
      },
      conditions: [],
      legends: [
        { type: 'rect', color: '#e04545', fillColor: '224,69,69', layerId: 'dnpj', name: '暴雨多年平均值（H）', groupName: '业务图层', isClick: true },
        { type: 'rect', color: '#7019ff', fillColor: '112,25,255', layerId: 'bcxs', name: '暴雨变差系数（Cv）', groupName: '业务图层', isClick: true },
        { type: 'rect', color: '#1cb55b', fillColor: '28,181,91', layerId: 'scyl', name: '历年实测雨量', groupName: '业务图层', isClick: true },
        { type: 'icon', url: require('@/assets/images/map/legend/DD.png'), layerId: 'station_DD', name: '堰闸水文站', groupName: '业务图层', isClick: true, needCluster: true },
        { type: 'icon', url: require('@/assets/images/map/legend/PP.png'), layerId: 'station_PP', name: '雨量站', groupName: '业务图层', isClick: true, needCluster: true },
        { type: 'icon', url: require('@/assets/images/map/legend/ZQ.png'), layerId: 'station_ZQ', name: '河道水文站', groupName: '业务图层', isClick: true, needCluster: true },
        { type: 'icon', url: require('@/assets/images/map/legend/ZZ.png'), layerId: 'station_ZZ', name: '河道水位站', groupName: '业务图层', isClick: true, needCluster: true },
        { type: 'icon', url: require('@/assets/images/map/legend/RR.png'), layerId: 'station_RR', name: '水库水文站', groupName: '业务图层', isClick: true, needCluster: true },
        { type: 'icon', url: require('@/assets/images/map/legend/QT.png'), layerId: 'station_QT', name: '其他测站', groupName: '业务图层', isClick: true, needCluster: true }
      ],
      metaSetMap: {
        dnpj: 'YSQJC_BYTJ_BYTJCG',
        bcxs: 'YSQJC_BYTJ_BYTJCG',
        scyl: 'YSQJC_BYTJ_BYTJCG',
        station_DD: 'YSQJC_ST_STBPRP_B_CB',
        station_PP: 'YSQJC_ST_STBPRP_B_CB',
        station_ZQ: 'YSQJC_ST_STBPRP_B_CB',
        station_ZZ: 'YSQJC_ST_STBPRP_B_CB',
        station_RR: 'YSQJC_ST_STBPRP_B_CB',
        station_QT: 'YSQJC_ST_STBPRP_B_CB'
      },
      methodCodeMap: {
        dnpj: 'select',
        bcxs: 'select',
        scyl: 'select',
        station_DD: 'getCZList',
        station_PP: 'getCZList',
        station_ZQ: 'getCZList',
        station_ZZ: 'getCZList',
        station_RR: 'getCZList',
        station_QT: 'getCZList'
      },
      methodParamsMap: {
        dnpj: { queryParam: { SJLX: '1', BZLSLX: '3' } },
        bcxs: { queryParam: { SJLX: '2', BZLSLX: '3' } },
        scyl: { queryParam: { SJLX: '3', BZLSLX: '3' } },
        station_DD: { CZXX: '', ZLMC: '堰闸水文站' },
        station_PP: { CZXX: '', ZLMC: '雨量站' },
        station_ZQ: { CZXX: '', ZLMC: '河道水文站' },
        station_ZZ: { CZXX: '', ZLMC: '河道水位站' },
        station_RR: { CZXX: '', ZLMC: '水库水文站' },
        station_QT: { CZXX: '', ZLMC: '其他站类' }
      },
      resultKey: {
        dnpj: 'KJDX',
        bcxs: 'KJDX',
        scyl: 'KJDX',
        station_DD: ['LGTD', 'LTTD'],
        station_PP: ['LGTD', 'LTTD'],
        station_ZQ: ['LGTD', 'LTTD'],
        station_ZZ: ['LGTD', 'LTTD'],
        station_RR: ['LGTD', 'LTTD'],
        station_QT: ['LGTD', 'LTTD']
      },
      searchLayers: ['dnpj'],
      firstLoaded: ['bcxs', 'scyl'],
      needClearLayer: ['dnpj', 'bcxs', 'scyl'],
      stationConfigs: {
        isView: false,
        appId: 'YSJC',
        bzCode: 'YSJC',
        metaSet: 'YSQJC_ST_STBPRP_B_CB',
        module: '站点',
        conditionProcessor: this.conditionProcessor,
        beforeFormSubmit: this.beforeSubmit
      },
      visible: false,
      BZLSLX: '3',
      expand: true
    }
  },
  methods: {
    async initLayersAndMenus () {
      await this.createLayers()
      this.setMenuItems()
      if (this.conditions.length) {
        this.updateMethodParams()
        this.getMapData()
      }
    },
    afterFetchColumns (columns) {
      for (const item of columns) {
        if (item.field === 'SCYLRQ') {
          item.visible = false
        }
      }
      this.columns = columns
      return columns
    },
    conditionLoaded (conditions) {
      const SJLXItem = conditions.find(item => item.field === 'SJLX')
      if (SJLXItem) {
        SJLXItem.type = 'checkbox'
      }
      const BZLSLXItem = conditions.find(item => item.field === 'BZLSLX')
      if (BZLSLXItem) {
        BZLSLXItem.type = 'radio'
      }
      this.conditions = conditions
      this.$refs.grid.connectCoditionForm(this.$refs.conditionForm)
      this.$nextTick(() => {
        this.reset()
        this.$refs.grid.refreshList({})
        if (this.layersLoaded) {
          this.updateMethodParams()
          this.getMapData()
        }
      })
    },
    reset () {
      this.$refs.conditionForm.setFormData({ BZLSLX: '3', SJLX: '1' })
    },
    search (data) {
      const col = this.columns.find(item => item.field === 'SCYLRQ')
      col.visible = data.SJLX.includes('3')
      this.$refs.grid.$refs.table.reloadColumn(this.columns)
      this.$refs.grid.refresh()
      this.updateMethodParams()
      this.getMapData()
      this.$refs.searchStation.getHtAndCv()
    },
    updateMethodParams () {
      const formData = this.$refs.conditionForm.getFormData()
      this.BZLSLX = formData.BZLSLX
      for (const key in this.methodParamsMap) {
        if (Object.hasOwnProperty.call(this.methodParamsMap, key)) {
          const element = this.methodParamsMap[key]
          if (key.startsWith('station_')) continue
          element.queryParam.BZLSLX = formData.BZLSLX
        }
      }
      if (formData.SJLX) {
        this.searchLayers = formData.SJLX.split(',').map(item => layerCodeMap[item])
      } else {
        this.searchLayers = ['dnpj', 'bcxs', 'scyl']
      }
    },
    afterFormLoading (form) {
      const { SJLX } = form.getFormData()
      this.changeType(SJLX)
    },
    customEditMethod (row) {
      this.isEdit = true
      this.$refs.grid.isEdit = true
      this.$refs.grid.$refs.form.show(row, true)
    },
    async formItemProcessor ({ items, rules }) {
      for (const item of items) {
        if (item.field === 'SJLX') {
          item.events = {
            change: this.changeType
          }
          item.props.mock = await this.$utils.dictionary.getOptionsByKey(item.props.dictionaryKey)
          debugger
          if (this.isEdit) {
            item.props.disabled = true
          } else {
            if (this.addType === 'Point') {
              item.props.disabled = true
            } else {
              item.props.mock = (await this.$utils.dictionary.getOptionsByKey(item.props.dictionaryKey)).slice(0, 2)
            }
          }
        }
        if (['TZZ', 'DWLX'].includes(item.field)) {
          item.props.disabled = true
        }
      }
      return { items, rules }
    },
    changeType (value) {
      if (value === '3') {
        this.$refs.grid.$refs.form.$refs.form.setItemVisible({
          SCYLRQ: true
        })
      } else {
        this.$refs.grid.$refs.form.$refs.form.setItemVisible({
          SCYLRQ: false
        })
      }

      this.$refs.grid.$refs.form.$refs.form.setFormData({ TZZ: value, DWLX: value })
    },
    async currentChange (row) {
      if (!row) return
      const layer = await this.$mapManager.invokeUtils('getLayer', layerCodeMap[row.SJLX])
      const feature = layer.getSource().getFeatureById(row.BYTJCGID)
      this.$mapManager.invoke('fit', feature.getGeometry(), { padding: [100, 700, 100, 200] })
      this.$mapManager.invoke('selectFeature', feature)
    },
    handleCommand (command) {
      this.isEdit = false
      this.addType = command
      this.$mapManager.invoke('showTool')
      this.$mapManager.invoke('startDrawByOptions', { type: command, eventKey: 'rainstorm-achievements' })
    },
    modifyEnd ({ result, length }) {
      if (this.isEdit) {
        this.$refs.grid.isEdit = true
        console.log(this.rowData.KJDX)
        const data = Object.assign({}, this.rowData, { KJDX: result })
        console.log(data.KJDX)
        this.$refs.grid.$refs.form.show(data, false)
      } else {
        this.$refs.grid.isEdit = false
        const { BZLSLX } = this.$refs.conditionForm.getFormData()

        this.$refs.grid.$refs.form.show({ KJDX: result, BZLSLX, SJLX: length ? '' : '3' }, false)
      }
    },
    handleOperation (operationName, row) {
      this[operationName](row)
    },
    async editSpot (row) {
      if (row.KJDX) {
        this.rowData = row
      }
      const layer = await this.$mapManager.invokeUtils('getLayer', 'modifylayer')
      layer.getSource().clear()
      const feature = await this.$mapManager.invoke('transfromFeature', this.rowData.KJDX)
      this.isEdit = true
      this.$mapManager.invoke('showTool', this.rowData.KJDX)
      this.$mapManager.invoke('startModifyByOptions', { feature, eventKey: 'rainstorm-achievements' })
      this.$mapManager.invoke('fit', feature.getGeometry(), { padding: [0, 500, 0, 100], maxZoom: 10 })
    },
    setMenuItems () {
      this.$mapManager.invoke('setContextMenuMethod', (feature, layerId, event) => {
        const properties = feature.getProperties()
        if (Object.hasOwn(properties, 'geometry')) {
          delete properties.geometry
        }
        this.rowData = properties
        if (['dnpj', 'bcxs', 'scyl'].includes(layerId)) {
          return [
            { text: '编辑', callback: this.editData },
            { text: '编辑边界', callback: this.editSpot },
            { text: '删除', callback: this.removeFeature }
          ]
        }
        return []
      })
    },
    removeFeature () {
      this.$refs.grid.removeRow(this.rowData)
    },
    editData () {
      this.$refs.grid.editRow(this.rowData)
    },
    stationHandleCommand (command) {
      this[command]()
    },
    async templateDownload () {
      const { data, fileName } = await this.$request.downloadFileByUrl('/profile/参编雨量站模板.xlsx', true)
      this.$request.downloadBlobFile(data, this.$helper.getRealFileName(fileName))
    },
    handleImport () {
      this.$refs.importButton.$el.click()
    },
    openStationManagement () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs.stationGrid.refreshList({})
      })
    },
    async importData ({ action, file }) {
      const data = await this.$request.upload(action, { file })
      this.$message.success('导入成功')
      if (this.$refs.stationGrid) {
        this.$refs.stationGrid.refresh()
      }
      const map = {}
      data.forEach(item => {
        const layerId = ['DD', 'PP', 'ZQ', 'ZZ', 'RR'].includes(item.STTP) ? `station_${item.STTP}` : 'station_QT'
        if (map[layerId]) {
          map[layerId].push(item)
        } else {
          map[layerId] = [item]
        }
      })
      for (const layerId in map) {
        if (Object.hasOwnProperty.call(map, layerId)) {
          const element = map[layerId]
          this.renderMapData(element, layerId)
        }
      }
    },
    clearPoint () {
      this.$mapManager.invoke('clearLayers')
      this.$mapManager.invoke('clearLayers', 'graphicLayer')
    },
    openModal () {
      this.$refs.modal.open()
    },
    conditionProcessor (conditions) {
      const item = conditions.find(item => item.field === 'STCD')
      item.label = '测站'
      return conditions
    },
    beforeSubmit (params) {
      const methodParams = JSON.parse(params.methodParams)
      methodParams.STNMPY = this.pinyin
      params.methodParams = JSON.stringify(methodParams)
      return params
    },
    async customValidator () {
      const formData = this.$refs.stationGrid.$refs.form.getFormData()
      this.pinyin = await this.$request.post('/ysjc/byjcg/getStnmPy', { STNM: formData.STNM })
      return true
    }
  },
  created () {
    this.$mapManager.addEventListener('mapModifyEnd-rainstorm-achievements', this.modifyEnd)
  },
  beforeCreate () {
    this.$mapManager.removeEventListener('mapModifyEnd-rainstorm-achievements', this.modifyEnd)
  }
}
</script>

<style lang="scss" scoped>
.import-upload {
  display: inline-block;
}

::v-deep .condition-form {
  height: auto;

  .el-form {
    padding: 0 10px;

    .el-form-item {
      margin-bottom: 0;
    }
  }

  .check-all {
    display: none;
  }

  .form-buttons {
    padding: 0;
    border: none;
    justify-content: flex-start;
    width: 100%;
    flex-direction: row-reverse;

    .el-button:first-child {
      margin: 0 10px;
    }

    .el-button {
      display: flex;
      align-items: center;
      justify-content: center;

      > i {
        margin-right: 6px;
      }
    }
  }
}

.panel-position {
  z-index: 9;
  position: absolute;
  left: 10px;
  top: 10px;
}

.follower-top {
  position: absolute;
  left: -40px;
  top: 0;
  transform: translateX(-100%);
}

.follower-bottom {
  position: absolute;
  z-index: 99;
  left: -10px;
  bottom: 0;
  transform: translateX(-100%);
}
</style>
